package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.dto.TrainTicketGroupDTO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.DailyTrainTicketMapper;
import com.ruoyi.business.domain.DailyTrainTicket;
import com.ruoyi.business.service.IDailyTrainTicketService;

/**
 * 余票信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class DailyTrainTicketServiceImpl implements IDailyTrainTicketService
{
    @Autowired
    private DailyTrainTicketMapper dailyTrainTicketMapper;

    /**
     * 查询余票信息
     *
     * @param id 余票信息主键
     * @return 余票信息
     */
    @Override
    public DailyTrainTicket selectDailyTrainTicketById(Long id)
    {
        return dailyTrainTicketMapper.selectDailyTrainTicketById(id);
    }

    /**
     * 查询余票信息列表
     *
     * @param dailyTrainTicket 余票信息
     * @return 余票信息
     */
    @Override
    public List<DailyTrainTicket> selectDailyTrainTicketList(DailyTrainTicket dailyTrainTicket)
    {
        return dailyTrainTicketMapper.selectDailyTrainTicketList(dailyTrainTicket);
    }

    /**
     * 新增余票信息
     *
     * @param dailyTrainTicket 余票信息
     * @return 结果
     */
    @Override
    public int insertDailyTrainTicket(DailyTrainTicket dailyTrainTicket)
    {
        dailyTrainTicket.setCreateTime(DateUtils.getNowDate());
        return dailyTrainTicketMapper.insertDailyTrainTicket(dailyTrainTicket);
    }

    /**
     * 修改余票信息
     *
     * @param dailyTrainTicket 余票信息
     * @return 结果
     */
    @Override
    public int updateDailyTrainTicket(DailyTrainTicket dailyTrainTicket)
    {
        dailyTrainTicket.setUpdateTime(DateUtils.getNowDate());
        return dailyTrainTicketMapper.updateDailyTrainTicket(dailyTrainTicket);
    }

    /**
     * 批量删除余票信息
     *
     * @param ids 需要删除的余票信息主键
     * @return 结果
     */
    @Override
    public int deleteDailyTrainTicketByIds(Long[] ids)
    {
        return dailyTrainTicketMapper.deleteDailyTrainTicketByIds(ids);
    }

    /**
     * 删除余票信息信息
     *
     * @param id 余票信息主键
     * @return 结果
     */
    @Override
    public int deleteDailyTrainTicketById(Long id)
    {
        return dailyTrainTicketMapper.deleteDailyTrainTicketById(id);
    }

    @Override
    public List<TrainTicketGroupDTO> selectDailyTrainTicketGroupByTrainCode(DailyTrainTicket dailyTrainTicket) {
        // 获取所有符合条件的车票数据(不分页)
        List<DailyTrainTicket> allTickets = dailyTrainTicketMapper.selectDailyTrainTicketList(dailyTrainTicket);

        // 按trainCode分组
        Map<String, List<DailyTrainTicket>> ticketGroups = allTickets.stream()
                .collect(Collectors.groupingBy(DailyTrainTicket::getTrainCode));

        // 转换为DTO对象
        List<TrainTicketGroupDTO> result = new ArrayList<>();

        for (Map.Entry<String, List<DailyTrainTicket>> entry : ticketGroups.entrySet()) {
            String trainCode = entry.getKey();
            List<DailyTrainTicket> tickets = entry.getValue();

            TrainTicketGroupDTO groupDTO = new TrainTicketGroupDTO();
            groupDTO.setTrainCode(trainCode);
            groupDTO.setTickets(tickets);

            // 设置主路线信息
            TrainTicketGroupDTO.MainRouteInfo mainRoute = calculateMainRoute(tickets);
            groupDTO.setMainRoute(mainRoute);

            result.add(groupDTO);
        }

        return result;
    }

    // 计算每组的主路线信息
    private TrainTicketGroupDTO.MainRouteInfo calculateMainRoute(List<DailyTrainTicket> tickets) {
        TrainTicketGroupDTO.MainRouteInfo mainRoute = new TrainTicketGroupDTO.MainRouteInfo();

        // 找出最大站序（修改为处理Long类型）
        long maxEndIndex = tickets.stream()
                .mapToLong(DailyTrainTicket::getEndIndex)
                .max()
                .orElse(0L);

        // 找出起始站(站序为0)（修改为处理Long类型）
        DailyTrainTicket startTicket = tickets.stream()
                .filter(t -> t.getStartIndex() != null && t.getStartIndex() == 0L)
                .findFirst()
                .orElse(null);

        // 找出终点站(到站序为最大)（修改为处理Long类型）
        List<DailyTrainTicket> endTickets = tickets.stream()
                .filter(t -> t.getEndIndex() != null && t.getEndIndex() == maxEndIndex)
                .collect(Collectors.toList());

        DailyTrainTicket endTicket = null;
        if (!endTickets.isEmpty()) {
            // 如果有多个到终点站的记录，选择出发站序最小的
            endTicket = endTickets.stream()
                    .min(Comparator.comparingLong(DailyTrainTicket::getStartIndex))
                    .orElse(null);
        }

        if (startTicket != null && endTicket != null) {
            mainRoute.setStart(startTicket.getStart());
            mainRoute.setStartTime(startTicket.getStartTime() != null ? startTicket.getStartTime().toString() : "");
            mainRoute.setEnd(endTicket.getEnd());
            mainRoute.setEndTime(endTicket.getEndTime() != null ? endTicket.getEndTime().toString() : "");
        } else if (!tickets.isEmpty()) {
            // 如果没有完全符合条件的记录，使用第一个记录的信息
            DailyTrainTicket firstTicket = tickets.get(0);
            mainRoute.setStart(firstTicket.getStart());
            mainRoute.setStartTime(firstTicket.getStartTime() != null ? firstTicket.getStartTime().toString() : "");
            mainRoute.setEnd(firstTicket.getEnd());
            mainRoute.setEndTime(firstTicket.getEndTime() != null ? firstTicket.getEndTime().toString() : "");
        }

        return mainRoute;
    }

    /**
     * 按列车分页查询余票信息
     */
    @Override
    public TableDataInfo listDailyTrainTicketByTrainGroup(DailyTrainTicket dailyTrainTicket, Integer pageNum, Integer pageSize) {
        // 计算分页偏移量
        int offset = (pageNum - 1) * pageSize;

        // 1. 分页查询符合条件的列车代码
        List<String> trainCodes = dailyTrainTicketMapper.selectTrainCodesWithPagination(
                dailyTrainTicket.getDate(),
                dailyTrainTicket.getTrainCode(),
                dailyTrainTicket.getStart(),
                dailyTrainTicket.getEnd(),
                pageSize,
                offset
        );

        // 2. 获取列车总数，用于分页
        int trainTotal = dailyTrainTicketMapper.countTrainCodes(
                dailyTrainTicket.getDate(),
                dailyTrainTicket.getTrainCode(),
                dailyTrainTicket.getStart(),
                dailyTrainTicket.getEnd()
        );

        // 3. 只查询分页后的车次的余票信息
        List<TrainTicketGroupDTO> result = new ArrayList<>();
        for (String trainCode : trainCodes) {
            // 创建查询条件，只查特定车次
            DailyTrainTicket query = new DailyTrainTicket();
            query.setDate(dailyTrainTicket.getDate());
            query.setTrainCode(trainCode);
            query.setStart(dailyTrainTicket.getStart());
            query.setEnd(dailyTrainTicket.getEnd());

            // 获取该车次所有车票
            List<DailyTrainTicket> tickets = dailyTrainTicketMapper.selectDailyTrainTicketList(query);

            if (!tickets.isEmpty()) {
                TrainTicketGroupDTO groupDTO = new TrainTicketGroupDTO();
                groupDTO.setTrainCode(trainCode);
                groupDTO.setTickets(tickets);

                // 设置主路线信息
                TrainTicketGroupDTO.MainRouteInfo mainRoute = calculateMainRoute(tickets);
                groupDTO.setMainRoute(mainRoute);

                result.add(groupDTO);
            }
        }

        // 4. 构建返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(result);
        rspData.setTotal(trainTotal); // 总列车数
        rspData.setMsg("查询成功");

        return rspData;
    }
}
